﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using OnlineVideos;
using OnlineVideos.Data;
using Common.Library;
using System.Windows.Media;
using AdRotator;
using System.Windows.Input;
using HtmlAgilityPack;
using System.Text.RegularExpressions;

namespace Social_Celebrities.Views
{    
    public partial class LinksFromOnline : PhoneApplicationPage
    {
        string SelectedText = string.Empty;
        string BlogType = string.Empty;
        IDictionary<string, List<string>> UrlList = new Dictionary<string, List<string>>();
        //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
        public List<string> NavigationHistory = new List<string>();
        public LinksFromOnline()
        {
            InitializeComponent();       
            this.Loaded += LinksFromOnline_Loaded;          
            this.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(BrowserPage_OrientationChanged);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {           
            NavigationContext.QueryString.TryGetValue("BlogType",out BlogType);                     
           //UrlList.Add("FaceBook", new List<string> { "https://www.facebook.com/search.php" });
           //UrlList.Add("Twitter", new List<string> { "https://twitter.com/filmorbit/lists/tollywood-celebrities", "https://twitter.com/filmorbit/lists/bollywood-celebrities" });
           //UrlList.Add("Twitter", new List<string> { "https://www.twitter.com/search-home" });
           //UrlList.Add("Twitter", new List<string> { "https://www.twitter.com" });
           UrlList.Add("Blogger", new List<string> { "https://www.google.co.in/"});
        }

        void LinksFromOnline_Loaded(object sender, RoutedEventArgs e)
        {
            //txtlink.ItemsSource = UrlList.Where(i => i.Key == BlogType).FirstOrDefault().Value;
            webBrowser1.Navigate(new Uri("https://www.google.co.in", UriKind.RelativeOrAbsolute));
        }

        void BrowserPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            try
            {
                if (e.Orientation == PageOrientation.Portrait || e.Orientation == PageOrientation.PortraitDown || e.Orientation == PageOrientation.PortraitUp)
                {
                    webBrowser1.Height = 740;
                    webBrowser1.Width = 480;
                    txtlink.Width = 410;
                    txtlink.Margin = new Thickness(0, -5, 0, 0);                   
                }
                else
                {
                    webBrowser1.Height = 420;
                    webBrowser1.Width = 800;
                    txtlink.Margin = new Thickness(0, -5, 0, 0);
                    txtlink.Width = 730;
                }
            }
            catch (Exception ex)
            {
                string excepmess = "Exception in BrowserPage_OrientationChanged Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }
               
        private void webBrowser1_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                webBrowser1.InvokeScript("eval", "function clickhandler(e){e.cancelBubble = true;var targetElement = e.target;var dataValue= document.selection.createRange().htmlText.toString().replace(/\\n/g, '').replace(/<br>/g, '<br />').replace(/\\r/g, '').replace(/\\t/g, ''); window.external.notify(dataValue);}");
                webBrowser1.InvokeScript("eval", "this.Add_eventHandler=function(e) {for (var i = 0; i < document.all.length; i++) {document.all[i].addEventListener(\"copy\", clickhandler);}}");
                webBrowser1.InvokeScript("Add_eventHandler");
                performanceProgressBar.IsIndeterminate = false;
            }
            catch
            {

            }
        }

        private void txtlink_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (txtlink.Text != "")
                {
                    txtmessage.Visibility = Visibility.Collapsed;
                    if (e.Key == Key.Enter)
                    {
                        if (!txtlink.Text.ToLower().StartsWith("http://") && !txtlink.Text.ToLower().StartsWith("https://"))
                        {
                            if (txtlink.Text.ToLower().Contains("www."))
                                txtlink.Text = "http://" + txtlink.Text;
                            else
                                txtlink.Text = "http://www." + txtlink.Text;
                        }
                        performanceProgressBar.IsIndeterminate = true;
                        webBrowser1.Navigate(new Uri(txtlink.Text, UriKind.RelativeOrAbsolute));
                    }
                }
                else
                {
                    txtmessage.Visibility = Visibility.Visible;                    
                }
            }
            catch (Exception ex)
            {
                string excepmess = "Exception in txtlink_KeyUp Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }
      
        private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!NavigationHistory.Contains(e.Uri.ToString()))
                NavigationHistory.Add(e.Uri.ToString());
        }

        private void txtlink_MouseEnter_1(object sender, MouseEventArgs e)
        {
            txtmessage.Visibility = Visibility.Collapsed;
        }
        public void NavigateBack()
        {
            try
            {
                webBrowser1.InvokeScript("eval", "history.go(-1)");
                NavigationHistory.RemoveAt(NavigationHistory.Count - 1);
            }
            catch
            {
                NavigationService.GoBack();
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (NavigationHistory.Count > 0)
            {
                e.Cancel = true;
                NavigateBack();
            }
            else
                base.OnBackKeyPress(e);
        }
        private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
        {
            try
            {
                if (e.Value != null)
                {
                        SelectedText = HttpUtility.HtmlDecode(Regex.Replace(e.Value.ToString(), "<[^>]+?>", ""));
                        MessageBoxResult result = default(MessageBoxResult);
                        result = MessageBox.Show("you have selected " + SelectedText, "", MessageBoxButton.OKCancel);
                        if (result == MessageBoxResult.OK)
                        {
                            Constants.SocialCelebrityId = SelectedText;
                            NavigationService.GoBack();
                        }
                }
            }
            catch
            {
            }
        }

        private void AutoCompleteBox_MouseEnter_1(object sender, MouseEventArgs e)
        {
        }

        private void AutoCompleteBox_MouseEnter_2(object sender, MouseEventArgs e)
        {
        }   
    }
}